/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.edu.uch.syscom.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import javax.faces.context.FacesContext;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import pe.edu.uch.syscom.commonService.ServiceFinder;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 *
 * @author USUARIO
 */
public class Print {

    private Connection connection;

    /**
     * Genera el buffer del reporte en PDF Antes utilizaba
     * 'JRBeanCollectionDataSource jrbcds' como paremetro
     *
     * @param jasper param parameters
     * @return
     */
    public ByteArrayOutputStream cargarReporte( String jasper, HashMap parameters ) {
        ByteArrayOutputStream buffer;
        try {
            buffer = new ByteArrayOutputStream();
            FacesContext context = FacesContext.getCurrentInstance();
            InputStream reportStream = context.getExternalContext().getResourceAsStream( jasper );

            if ( connection == null || connection.isClosed() ) {
                DriverManagerDataSource dmds = (DriverManagerDataSource) ServiceFinder.findBean( "dataSource" );
                connection = dmds.getConnection();
            }
            JasperPrint jasperPrint = JasperFillManager.fillReport( reportStream, parameters, connection );
            JasperExportManager.exportReportToPdfStream( jasperPrint, buffer );

        } catch ( Exception e ) {
            e.printStackTrace();
            buffer = null;
        }
        return buffer;
    }

    public void cerrarConexion() {
        try {
            if ( connection != null && !connection.isClosed() ) {
                connection.close();
            }
        } catch ( Exception ex ) {
            ex.printStackTrace();
        }
    }
}
